/**
 *
 */
package pt.mleiria.socket.server;

import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author manuel
 *
 */
public class VoiceServer extends Thread {

    private static final int portVoiceServer = 69;
    final private ServerSocket serverSocket;
    private final String FILE_EXT = ".txt";
    private String lang;

    public VoiceServer() throws IOException {
        serverSocket = new ServerSocket(portVoiceServer);
        //serverSocket.setSoTimeout(10000);
    }

    @Override
    public void run() {
        Socket server = null;
        try {
            while (true) {
                Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "Waiting for client on port "
                        + serverSocket.getLocalPort() + "...");
                server = serverSocket.accept();
                Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "Just connected to "
                        + server.getRemoteSocketAddress());
                DataInputStream in
                        = new DataInputStream(server.getInputStream());
                
                
                String command = in.readUTF();
                String[] commandArr = command.split(";");

                if (commandArr[0].equals("ml_kill")) {
                    server.close();
                    break;
                }
                lang = commandArr[0];
                Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "[lang]:" + lang + ":");
                for (int i = 1; i < commandArr.length; i++) {
                    final String fileName = "voice" + i;
                    createFile(commandArr[i], fileName);
                    talk(fileName + FILE_EXT);
                }
            }
        } catch (SocketTimeoutException s) {
            Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "Socket timed out!");
            s.printStackTrace();
            try {
                server.close();
            } catch (IOException ex) {
                Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                server.close();
            } catch (IOException ex) {
                Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            Thread t = new VoiceServer();
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private boolean createFile(final String content, final String fileName) {
        PrintWriter writer;
        try {

            Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "[content]:" + content + ":");
            writer = new PrintWriter(fileName + FILE_EXT, "UTF-8");
            writer.println(content);
            writer.close();
            //Thread.sleep(2000);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } //catch (InterruptedException ex) {
        //Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, ex);
        //}
        return true;
    }

    private boolean talk(final String fileName) {

        //StringBuffer output = new StringBuffer();
        Process p;
        try {
            final String runTimeCommand = "espeak -v" + lang + "+f2 -s 90 -f " + fileName;
            Logger.getLogger(VoiceServer.class.getName()).log(Level.INFO, "[Runtimer:]"+runTimeCommand);
            p = Runtime.getRuntime().exec(runTimeCommand);
            p.waitFor();
            return true;
            /*
             BufferedReader reader
             = new BufferedReader(new InputStreamReader(p.getInputStream()));

             String line = "";
             while ((line = reader.readLine()) != null) {
             output.append(line + "\n");
             }
             */
        } catch (Exception e) {
            Logger.getLogger(VoiceServer.class.getName()).log(Level.SEVERE, null, e);
            return false;
        }
        //return output.toString();
    }

}
